﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Collections;

namespace Alex.Library.Web.Mvc
{
    public class UploadFileSizeAttribute : ActionFilterAttribute
    {
        public UploadFileSizeAttribute(int maxBytes)
        {
            this.MaxBytes = maxBytes;
        }

        public UploadFileSizeAttribute()
        {
        }

        public int MaxBytes { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (this.MaxBytes > 0)
            {
                Hashtable hash = new Hashtable();
                if (HttpContext.Current.Request.Files.Count == 0 || HttpContext.Current.Request.Files[0] == null)
                {
                    hash["error"] = 1;
                    hash["message"] = "上传文件不能为空！";
                    JsonResult result = GetResult(hash);
                    filterContext.Result = result;
                    return;
                }

                HttpPostedFile file = HttpContext.Current.Request.Files[0];
                if (file.InputStream == null || file.InputStream.Length > MaxBytes * 1024)
                {                    
                    hash["error"] = 1;
                    hash["message"] = String.Format("上传文件大小不能超过{0}M！", MaxBytes / 1024);
                    JsonResult result = GetResult(hash);
                    filterContext.Result = result;
                    return;
                }
            }
            base.OnActionExecuting(filterContext);
        }

        private JsonResult GetResult(Hashtable hash)
        {
            JsonResult result = new JsonResult();
            result.ContentEncoding = Encoding.UTF8;
            result.ContentType = "text/html;charset=UTF-8";
            result.Data = hash;
            return result;
        }
    }
}
